
import ruleTrigger from './ruleTrigger'
const tags = {
  // 输入框
  'el-input': (data, formConfig) => {
    const {
      tag, disabled, vModel, clearable, placeholder, width
    } = attrBuilder(data, formConfig)
    const maxlength = data.attributes.maxlength ? `:maxlength="${data.attributes.maxlength}"` : ''   // 输入框占位文本
    const showWordLimit = data.attributes['show-word-limit'] ? 'show-word-limit' : ''
    const readonly = data.attributes.readonly ? 'readonly' : ''
    const prefixIcon = data.attributes['prefix-icon'] ? `prefix-icon='${data.attributes['prefix-icon']}'` : ''
    const suffixIcon = data.attributes['suffix-icon'] ? `suffix-icon='${data.attributes['suffix-icon']}'` : ''
    const showPassword = data.attributes['show-password'] ? 'show-password' : ''
    const type = data.type && data.type !== "input" ? `type="${data.type}"` : ''
    const autosize = data.attributes.autosize && data.attributes.autosize.minRows
      ? `:autosize="{minRows: ${data.attributes.autosize.minRows}, maxRows: ${data.attributes.autosize.maxRows}}"`
      : ''
    let child = builddataInputChild(data)
    if (child) child = `\n${child}\n` // 换行
    return `<${tag} ${vModel} ${type} ${placeholder} ${maxlength} ${showWordLimit} ${readonly} ${disabled} ${clearable} ${prefixIcon} ${suffixIcon} ${showPassword} ${autosize} ${width}>${child}</${tag}>`
  },
  'el-select': (data, formConfig) => {
    const {
      tag, disabled, vModel, clearable, placeholder, width
    } = attrBuilder(data, formConfig)
    const filterable = data.attributes.filterable ? 'filterable' : ''
    const multiple = data.multiple ? 'multiple' : ''
    let child = buildElSelectChild(data)

    if (child) child = `\n${child}\n` // 换行
    return `<${tag} ${vModel} ${placeholder} ${disabled} ${multiple} ${filterable} ${clearable} ${width}>${child}</${tag}>`
  },
  number: data => {
    return `<data-input v-moddata="input" placeholder="请输入内容"></data-input>`
  },

  sdataect: data => {
    return ` <data-sdataect
    v-moddata="value"
    :placeholder="currentItem.attributes.placeholder"
  >
    <data-option
      v-for="item in options"
      :key="item.value"
      :labdata="item.labdata"
      :value="item.value"
    >
    </data-option>
  </data-sdataect>`
  },

  'el-checkbox-group': (data, formConfig) => {
    const { tag, disabled, vModel } = attrBuilder(data, formConfig)
    const size = `size="${data.attributes.size}"`
    const min = data.attributes.min ? `:min="${data.attributes.min}"` : ''
    const max = data.attributes.max ? `:max="${data.attributes.max}"` : ''
    let child = buildElCheckboxGroupChild(data)

    if (child) child = `\n${child}\n` // 换行
    return `<${tag} ${vModel} ${min} ${max} ${size} ${disabled}>${child}</${tag}>`
  },
  'el-radio-group': (data, formConfig) => {
    const { tag, disabled, vModel } = attrBuilder(data, formConfig)
    const size = `size="${data.attributes.size}"`
    let child = buildElRadioGroupChild(data)

    if (child) child = `\n${child}\n` // 换行
    return `<${tag} ${vModel} ${size} ${disabled}>${child}</${tag}>`
  },
  'el-date-picker': (data, formConfig) => {
    const {
      tag, disabled, vModel, clearable, placeholder, width
    } = attrBuilder(data, formConfig)
    const startPlaceholder = data.attributes['start-placeholder'] ? `start-placeholder="${data.attributes['start-placeholder']}"` : ''
    const endPlaceholder = data.attributes['end-placeholder'] ? `end-placeholder="${data.attributes['end-placeholder']}"` : ''
    const rangeSeparator = data.attributes['range-separator'] ? `range-separator="${data.attributes['range-separator']}"` : ''
    const format = data.attributes.format ? `format="${data.attributes.format}"` : ''
    const valueFormat = data.attributes['value-format'] ? `value-format="${data.attributes['value-format']}"` : ''
    const type = data.attributes.type === 'date' ? '' : `type="${data.attributes.type}"`
    const readonly = data.attributes.readonly ? 'readonly' : ''

    return `<${tag} ${type} ${vModel} ${format} ${valueFormat} ${width} ${placeholder} ${startPlaceholder} ${endPlaceholder} ${rangeSeparator} ${clearable} ${readonly} ${disabled}></${tag}>`
  },
  'el-time-picker': (data, formConfig) => {
    const {
      tag, disabled, vModel, clearable, placeholder, width
    } = attrBuilder(data, formConfig)
    const startPlaceholder = data.attributes['start-placeholder'] ? `start-placeholder="${data.attributes['start-placeholder']}"` : ''
    const endPlaceholder = data.attributes['end-placeholder'] ? `end-placeholder="${data.attributes['end-placeholder']}"` : ''
    const rangeSeparator = data.attributes['range-separator'] ? `range-separator="${data.attributes['range-separator']}"` : ''
    const isRange = data.attributes['is-range'] ? 'is-range' : ''
    const format = data.attributes.format ? `format="${data.attributes.format}"` : ''
    const valueFormat = data.attributes['value-format'] ? `value-format="${data.attributes['value-format']}"` : ''
    const pickerOptions = data.attributes['picker-options'] ? `:picker-options='${JSON.stringify(data.attributes['picker-options'])}'` : ''

    return `<${tag} ${vModel} ${isRange} ${format} ${valueFormat} ${pickerOptions} ${width} ${placeholder} ${startPlaceholder} ${endPlaceholder} ${rangeSeparator} ${clearable} ${disabled}></${tag}>`
  },
  'el-rate': (data, formConfig) => {
    const { tag, disabled, vModel } = attrBuilder(data, formConfig)
    const max = data.attributes.max ? `:max='${data.attributes.max}'` : ''
    const allowHalf = data.attributes['allow-half'] ? 'allow-half' : ''
    const showText = data.attributes['show-text'] ? 'show-text' : ''
    const showScore = data.attributes['show-score'] ? 'show-score' : ''

    return `<${tag} ${vModel} ${max} ${allowHalf} ${showText} ${showScore} ${disabled}></${tag}>`
  },
  'el-slider': (data, formConfig) => {
    const { tag, disabled, vModel } = attrBuilder(data, formConfig)
    const min = data.attributes.min ? `:min='${data.attributes.min}'` : ''
    const max = data.attributes.max ? `:max='${data.attributes.max}'` : ''
    const step = data.attributes.step ? `:step='${data.attributes.step}'` : ''
    const range = data.attributes.range ? 'range' : ''
    const showStops = data.attributes['show-stops'] ? `:show-stops="${data.attributes['show-stops']}"` : ''

    return `<${tag} ${min} ${max} ${step} ${vModel} ${range} ${showStops} ${disabled}></${tag}>`
  },
  uploadFile: data => {
    return `<data-input v-moddata="input" placeholder="请输入内容"></data-input>`
  }, uploadImg: data => {
    return `<data-input v-moddata="input" placeholder="请输入内容"></data-input>`
  },
  'el-cascader': (data, formConfig) => {
    const {
      tag, disabled, vModel, clearable, placeholder, width
    } = attrBuilder(data, formConfig)
    const options = data.attributes.options ? `:options="${data.model}Options"` : ''
    const props = data.attributes.props ? `:props="${data.model}Props"` : ''
    const showAllLevels = data.attributes['show-all-levels'] ? '' : ':show-all-levels="false"'
    const filterable = data.attributes.filterable ? 'filterable' : ''
    const separator = data.attributes.separator === '/' ? '' : `separator="${data.attributes.separator}"`

    return `<${tag} ${vModel} ${options} ${props} ${width} ${showAllLevels} ${placeholder} ${separator} ${filterable} ${clearable} ${disabled}></${tag}>`
  },
  'el-switch': (data, formConfig) => {
    const { tag, disabled, vModel } = attrBuilder(data, formConfig)
    const activeText = data.attributes['active-text'] ? `active-text="${data.attributes['active-text']}"` : ''
    const inactiveText = data.attributes['inactive-text'] ? `inactive-text="${data.attributes['inactive-text']}"` : ''
    const activeColor = data.attributes['active-color'] ? `active-color="${data.attributes['active-color']}"` : ''
    const inactiveColor = data.attributes['inactive-color'] ? `inactive-color="${data.attributes['inactive-color']}"` : ''
    const activeValue = data.attributes['active-value'] !== true ? `:active-value='${JSON.stringify(data.attributes['active-value'])}'` : ''
    const inactiveValue = data.attributes['inactive-value'] !== false ? `:inactive-value='${JSON.stringify(data.attributes['inactive-value'])}'` : ''

    return `<${tag} ${vModel} ${activeText} ${inactiveText} ${activeColor} ${inactiveColor} ${activeValue} ${inactiveValue} ${disabled}></${tag}>`
  },
  alert: data => {
    return ` <data-alert
    title="成功提示的文案"
    type="success"
  >
  </data-alert>`
  }
}

function attrBuilder(data, formConfig) {
  return {
    tag: data.tag,
    vModel: `v-model="${formConfig.formModel}.${data.model}"`,
    clearable: data.attributes.clearable ? 'clearable' : '',
    placeholder: data.attributes.placeholder ? `placeholder="${data.attributes.placeholder}"` : '',
    width: data.style && data.style.width ? ':style="{width: \'100%\'}"' : '',
    disabled: data.attributes.disabled ? 'disabled' : ''
  }
}

// data-input 子级
function builddataInputChild(scheme) {
  const children = []
  const slot = scheme.slot
  if (slot && slot.prepend) {
    children.push(`<template slot="prepend">${slot.prepend}</template>`)
  }
  if (slot && slot.append) {
    children.push(`<template slot="append">${slot.append}</template>`)
  }
  return children.join('\n')
}


// el-select 子级
function buildElSelectChild(scheme) {
  const children = []
  const slot = scheme.slot
  if (slot && slot.options && slot.options.length) {
    children.push(`<el-option v-for="(item, index) in ${scheme.model}Options" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>`)
  }
  return children.join('\n')
}


// el-checkbox-group 子级
function buildElCheckboxGroupChild(scheme) {
  const children = []
  const slot = scheme.slot
  const attributes = scheme.attributes
  if (slot && slot.options && slot.options.length) {
    const tag = attributes.optionType === 'button' ? 'el-checkbox-button' : 'el-checkbox'
    const border = attributes.border ? 'border' : ''
    children.push(`<${tag} v-for="(item, index) in ${scheme.model}Options" :key="index" :label="item.value" :disabled="item.disabled" ${border}>{{item.label}}</${tag}>`)
  }
  return children.join('\n')
}
// el-radio-group 子级
function buildElRadioGroupChild(scheme) {
  const children = []
  const slot = scheme.slot
  const attributes = scheme.attributes
  if (slot && slot.options && slot.options.length) {
    const tag = attributes.optionType === 'button' ? 'el-radio-button' : 'el-radio'
    const border = attributes.border ? 'border' : ''
    children.push(`<${tag} v-for="(item, index) in ${scheme.model}Options" :key="index" :label="item.value" :disabled="item.disabled" ${border}>{{item.label}}</${tag}>`)
  }
  return children.join('\n')
}



// 组装el-form
function buildFormTemplate(child, formConfig) {
  let labelPosition = ''
  if (formConfig.labelPosition !== 'right') {
    labelPosition = `label-position="${formConfig.labelPosition}"`
  }
  const disabled = formConfig.disabled ? `:disabled="${formConfig.disabled}"` : ''
  let str = `<el-form ref="${formConfig.formRef}" :model="${formConfig.formModel}" :rules="${formConfig.formRules}" size="${formConfig.size}" ${disabled} label-width="${formConfig.labelWidth}px" ${labelPosition}>
      ${child}
      
    </el-form>`
  // if (someSpanIsNot24) {
  //   str = `<el-row :gutter="${formConfig.gutter}">
  //       ${str}
  //     </el-row>`
  // }
  return str
}
// span不为24的用el-col包裹
function colWrapper(formConfig, str) {
  if (formConfig.attributes.span !== 24) {
    return `<el-col :span="${formConfig.span}">
      ${str}
    </el-col>`
  }
  return str
}

const layouts = {
  colFormItem(dataement, formConfig) {

    let labelWidth = ''
    let label = `label="${dataement.label}"`
    if (formConfig.labelWidth) {
      labelWidth = `label-width="${formConfig.labelWidth}px"`
    }
    const prop = dataement.attributes.required || dataement.rules.length > 0 ? `prop="${dataement.model}"` : ''
    const required = !ruleTrigger[dataement.tag] && dataement.attributes.required ? 'required' : ''
    const tagDom = tags[dataement.tag] ? tags[dataement.tag](dataement, formConfig) : null
    let str = `<el-form-item ${labelWidth} ${label} ${prop} ${required}>
        ${tagDom}
      </el-form-item>`

    return str
  },
  rowFormItem(scheme) {
    const config = scheme.attributes
    const type = scheme.type === 'default' ? '' : `type="${scheme.type}"`
    const justify = scheme.type === 'default' ? '' : `justify="${scheme.justify}"`
    const align = scheme.type === 'default' ? '' : `align="${scheme.align}"`
    const gutter = scheme.gutter ? `:gutter="${scheme.gutter}"` : ''
    const children = config.children.map(el => layouts[el.attributes.layout](el))
    let str = `<el-row ${type} ${justify} ${align} ${gutter}>
      ${children.join('\n')}
    </el-row>`

    return str
  }
}
export function makeUpHtml(data, formConfig) {
  let htmlList = []
  // 循环每个formItem配置
  data.forEach(dataement => {
    // 组装每个formItem代码
    htmlList.push(layouts.colFormItem(dataement, formConfig))
  });
  const htmlStr = htmlList.join('\n')
  // 将组件代码放进form标签
  let temp = buildFormTemplate(htmlStr, formConfig)
  return temp
}

export function vueTemplate(str) {
  return `<template>
    <div>
      ${str}
    </div>
  </template>`
}
export function vueScript(str) {
  return `<script>
    ${str}
  </script>`
}
export function cssStyle(cssStr) {
  return `<style  lang="scss" scoped>
    ${cssStr}
  </style>`
}